package com.kzj.mls.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.util.AbLogUtil;
import com.ab.util.AbViewUtil;
import com.kzj.mls.R;
import com.kzj.mls.global.App;
import com.kzj.mls.global.AppManager;
import com.kzj.mls.global.Constant;
import com.kzj.mls.recyclerCard.basic.MaterialListAdapter;
import com.kzj.mls.test.TextCropImageActivity;
import com.kzj.mls.widget.dialog.SweetDialogManager;
import com.umeng.analytics.MobclickAgent;


/**
 * @author yaomingLu
 * @version V4.0.1
 * @since 2015-4-2
 * <p/>
 * <pre>
 * 抽象基类
 * </pre>
 */
public abstract class GBaseActivity extends FragmentActivity implements
        OnClickListener {
    public String TAG = "";
    /**
     * 主内容布局.
     */
    private FrameLayout mMiddleContent;
    private RelativeLayout mTopbar;
    private ImageView mLeftImg;
    private ImageView mRightImg;
    private TextView mLeftText;
    private TextView mRightText;
    private TextView mTitleText;
    public TextView textView_address;
    /**
     * 主标题布局.
     */
    private RelativeLayout mtitleContent;
    //public LoadingDialog progressDlg;
    public boolean isOnStopActivity;
    private PopupWindow mPopupWindow;

    public boolean isUsePx;
    private ImageView mBottomLine;
    private ImageView mCenterImg;
    private ImageView imageView_address;
    private LinearLayout mRightDefineLinearlayout;
    private LinearLayout linearlayout_left_address;

    /**
     * ********************************* start GBaseActivity的生命周期 ***********************************************************************
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getName();
        if (Constant.SystemContext.isDebugShowToast) {
            App.showToast(TAG);
            AbLogUtil.e("当前activity", TAG);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 将标题栏去掉
        super.setContentView(R.layout.activity_base);
        AppManager.getAppManager().addActivity(this); // 将activity推入管理栈
        initTopBar();
        initMiddleView();
    }

    protected abstract void findViewByIds();

    protected abstract void initDatas();

    protected abstract void fillArrayInListView();

    /**
     * 子类调用此方法前会先调用BaseActivity的onCreate初始化各种view
     */
    @Override
    public void setContentView(int layoutResID) {
        View v = null;
        try {
            v = View.inflate(this, layoutResID, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LayoutParams params = mMiddleContent.getLayoutParams();
        params.width = LayoutParams.FILL_PARENT;
        params.height = LayoutParams.FILL_PARENT;
        if (v != null) {
            mMiddleContent.addView(v, params);
        } else {
            v = View.inflate(this, layoutResID, null);
            mMiddleContent.addView(v, params);
        }

    }

    /**
     * 这方法在写xml注意在720*1280上面设置像素px
     */
    public void setContentViewFor720_1280(int layoutResID) {

        setContentView(layoutResID);
        isUsePx = true;
    }

    public void setContentView(View v) {
        LayoutParams params = mMiddleContent.getLayoutParams();
        params.width = LayoutParams.FILL_PARENT;
        params.height = LayoutParams.FILL_PARENT;
        mMiddleContent.addView(v, params);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isOnStopActivity = false;
        MaterialListAdapter.isNeedSacleItem = isUsePx;
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPause(this);

    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, arg2);
        MaterialListAdapter.isNeedSacleItem = isUsePx;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isOnStopActivity = true;
    }

    @Override
    protected void onDestroy() { // 销毁时activity出栈
        AppManager.getAppManager().finishActivity(this);

        super.onDestroy();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        AbLogUtil.e("onRestoreInstanceState", this.getClass().getSimpleName());
        finish();
        startActivity(new Intent(this, MainActivity.class));
    }

    /************************************ end GBaseActivity的生命周期 ************************************************************************/


    /**
     * 显示加载框
     */
    public void showLoadingDialog() {
        /*if (progressDlg != null && progressDlg.isShowing()) {

		} else {
			if (!this.isFinishing() && !isOnStopActivity) {
				progressDlg = LoadingDialog.create(this);
				progressDlg.show();
			}
		}*/
        SweetDialogManager.getInstance().showDialogByProgress(this, "Loading");
    }

    /**
     * 关闭加载框
     */
    public void dismissDialog() {
		/*if (progressDlg != null && progressDlg.isShowing()
				&& !this.isFinishing()) {
			progressDlg.cancel();
		}*/
        SweetDialogManager.getInstance().dismissSweetDialog(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (Constant.SystemContext.isDebugLog) {
            menu.add(0, 0, 0, "请求/响应日志");
            menu.add(1, 1, 1, "crash闪退日志");
            menu.add(2, 2, 2, "showRequestToast");
            menu.add(3, 3, 3, "商家版");
        }
        return true;
    }

    /**
     * 部分手机无法使用菜单键 ，可以从此处进入
     */
    /**
     *
     */
    @SuppressWarnings("deprecation")
    private void initTestPopupWindow() {
        LinearLayout contentview = (LinearLayout) getLayoutInflater().inflate(
                R.layout.testpopupwindow, null);
        Button button1 = (Button) contentview.findViewById(R.id.button1);
        Button button2 = (Button) contentview.findViewById(R.id.button2);
        Button button3 = (Button) contentview.findViewById(R.id.button3);
        Button button4 = (Button) contentview.findViewById(R.id.button4);
        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // response
                startActivity(new Intent(getApplicationContext(),
                        ServerLogActivity.class));
                mPopupWindow.dismiss();
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // crash
                startActivity(new Intent(getApplicationContext(),
                        ServerLogActivity.class).putExtra("crash", "crash"));
                mPopupWindow.dismiss();
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // uitest
			/*	startActivity(new Intent(getApplicationContext(),
						TestFunctionActivity2.class));*/

                Constant.SystemContext.ROOT_URL_VALUE = Constant.SystemContext.OfficialUrl;
                mPopupWindow.dismiss();
            }
        });
        button4.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Constant.SystemContext.ROOT_URL_VALUE = Constant.SystemContext.TestUrl;
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow = new PopupWindow(contentview,
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.color.white));
        mPopupWindow.setOutsideTouchable(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                startActivity(new Intent(getApplicationContext(),
                        ServerLogActivity.class));
                break;
            case 1:
                startActivity(new Intent(getApplicationContext(),
                        ServerLogActivity.class).putExtra("crash", "crash"));
                break;
            case 2:
                if (Constant.SystemContext.isDebugShowToast) {
                    Constant.SystemContext.isDebugShowToast = false;
                } else {
                    Constant.SystemContext.isDebugShowToast = true;
                }
                // gotoActivity(SuperProjectDetailActivity.class, null);
                //gotoActivity(TestActivity.class, null);
			/*Intent intent = new Intent(getActivity(), WebActivity.class);
			intent.putExtra(WebActivity.Title, "广告预览");
			intent.putExtra(WebActivity.RightTest, "分享");
			intent.putExtra(WebActivity.WebUrl, "http://192.168.0.138:8080/GmallBaseServer/gmall/P-center/turnover.jsp");
			startActivity(intent);*/

                break;
            case 3:
                startActivity(new Intent(getApplicationContext(),
                        TextCropImageActivity.class));
			/*startActivity(new Intent(getApplicationContext(),
					HomeActivity_shangjia.class));
			if (!AppManager.getAppManager().currentActivity().toString().contains("HomeActivity_shangjia")) {
				finish();
			}*/

                break;

        }

        return true;
    }

    /************************************ end 加载对话框 与 基础菜单功能 ************************************************************************/

    /************************************ start GBaseActivity的标题栏设置方式 ************************************************************************/
    /**
     * 初始化中间内容
     */
    private void initMiddleView() {
        mMiddleContent = (FrameLayout) findViewById(R.id.ui_content);
    }

    /**
     * @return 获取整个顶部栏
     */
    public View getTopBar() {
        return mTopbar;
    }

    /**
     * @return 只获取中间的标题
     */
    public TextView getTopTitle() {
        return mTitleText;
    }

    /**
     * 初始化标题栏
     */
    private void initTopBar() {
        mTopbar = (RelativeLayout) findViewById(R.id.topbar);
        mtitleContent = (RelativeLayout) findViewById(R.id.ll_title_content);
        mLeftImg = (ImageView) findViewById(R.id.iv_leftimg);
        mRightImg = (ImageView) findViewById(R.id.iv_rightimg);
        mBottomLine = (ImageView) findViewById(R.id.bottomline);
        mCenterImg = (ImageView) findViewById(R.id.iv_centerimg);
        mLeftText = (TextView) findViewById(R.id.tv_lefttext);
        mRightText = (TextView) findViewById(R.id.tv_righttext);
        mTitleText = (TextView) findViewById(R.id.tv_title);
        textView_address = (TextView) findViewById(R.id.textView_address);
        imageView_address = (ImageView) findViewById(R.id.imageView_address);
        linearlayout_left_address = (LinearLayout) findViewById(R.id.linearlayout_left_address);
        mRightDefineLinearlayout = (LinearLayout) findViewById(R.id.linearlayout_right_define);

        linearlayout_left_address.setOnClickListener(this);
        mTitleText.setOnClickListener(this);
        mLeftImg.setOnClickListener(this);
        mRightImg.setOnClickListener(this);
        mLeftText.setOnClickListener(this);
        mRightText.setOnClickListener(this);
        mTitleText.setOnClickListener(this);
        mCenterImg.setOnClickListener(this);
        initGoneTopBarView();
        AbViewUtil.scaleContentView(mTopbar);

    }

    /**
     * 开始全部隐藏控件
     */
    private void initGoneTopBarView() {
        linearlayout_left_address.setVisibility(View.GONE);
        mTitleText.setVisibility(View.GONE);
    }

    public void showLeftAddress(int visibility, String addressTitle) {
        linearlayout_left_address.setVisibility(visibility);
        textView_address.setText(addressTitle);
    }

    public void setImageViewAddressVisibility(int visibility) {
        imageView_address.setVisibility(visibility);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_leftimg:
                doClickLeftImg();
                break;
            case R.id.iv_rightimg:
                doClickRightImg();
                break;
            case R.id.tv_lefttext:
                doClickLeftText();
                break;
            case R.id.tv_righttext:
                doClickRightText();
                break;
            case R.id.tv_title:
                doClickTitle();
                break;
            case R.id.iv_centerimg:
                doClickCenterImg();
                break;
            case R.id.linearlayout_left_address:
                if (null != textView_address.getText()) {
                    doClickAddress(textView_address.getText().toString());
                } else {
                    doClickAddress("");
                }
                break;
            default:
                break;
        }
    }

    /**
     *  设置标题栏 左边自定义的布局
     * @param view 自定义布局
     */
/*	public void setLeftDefinedLinearLayout(int visibility,View view) {
		mLeftDefineLinearlayout.removeAllViews();
		mLeftDefineLinearlayout.addView(view,
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		mLeftDefineLinearlayout.setVisibility(visibility);
	}*/

    /**
     * 设置标题栏 右边自定义的布局
     *
     * @param view 自定义布局
     */
    public void setRightDefineLinearLayout(int visibility, View view) {
        mRightDefineLinearlayout.removeAllViews();
        mRightDefineLinearlayout.addView(view,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        mRightDefineLinearlayout.setVisibility(visibility);
    }

    /**
     * 设置头部的底部线的可见性，默认不可见
     *
     * @param visible
     */
    public void setBottomLine(int visible) {
        mBottomLine.setVisibility(visible);
    }

    /**
     * 设置topbar的背景资源图 默认高度为50
     *
     * @param resId
     */
    public void setTitleBarBackground(int resId) {
        mtitleContent.setBackgroundResource(resId);
    }

    /**
     * 设置标题文字的颜色
     *
     * @param color
     */
    public void setTitleTextColor(int color) {
        mTitleText.setTextColor(color);
    }

    /**
     * 设置左边字体的颜色
     *
     * @param color
     */
    public void setLeftTextColor(int color) {
        mLeftText.setTextColor(color);
    }

    /**
     * 设置右边字体的颜色
     *
     * @param color
     */
    public void setRightTextColor(int color) {
        mRightText.setTextColor(color);
    }

    /**
     * 设置左边的图片,已经默认设置点击事件为关闭当前页面
     *
     * @param visibility
     * @param resId
     */
    public void setLeftImg(int visibility, int resId) {
        mLeftImg.setVisibility(visibility);
        mLeftImg.setImageResource(resId);
    }

    /**
     * 设置右边的图片
     *
     * @param visibility
     * @param resId
     */
    public void setRightImg(int visibility, int resId) {
        mRightImg.setVisibility(visibility);
        mRightImg.setImageResource(resId);
    }

    /**
     * 设置左边的文字
     *
     * @param visibility
     * @param resId
     */
    public void setleftText(int visibility, int resId) {
        mLeftText.setVisibility(visibility);
        mLeftText.setText(resId);
    }

    /**
     * 设置左边的文字
     *
     * @param visibility
     * @param string
     */
    public void setleftText(int visibility, String string) {
        mLeftText.setVisibility(visibility);
        mLeftText.setText(string);
    }

    /**
     * 设置右边的文字
     *
     * @param visibility
     * @param resId
     */
    public void setRightText(int visibility, int resId) {
        mRightText.setVisibility(visibility);
        mRightText.setText(resId);
    }

    /**
     * 设置右边的文字
     *
     * @param visibility
     * @param string
     */
    public void setRightText(int visibility, String string) {
        mRightText.setVisibility(visibility);
        mRightText.setText(string);
    }

    /**
     * 设置中间的title
     *
     * @param resId
     */
    public void setTopTitle(int resId) {
        mTitleText.setVisibility(View.VISIBLE);
        mTitleText.setText(resId);
    }

    /**
     * 设置中间的title
     *
     * @param text
     */
    public void setTopTitle(String text) {
        mTitleText.setVisibility(View.VISIBLE);
        mTitleText.setText(text);
    }

    /**
     * 设置中间img
     *
     * @param visibility
     * @param resId
     */
    public void setCenterImg(int visibility, int resId) {
        mCenterImg.setVisibility(visibility);
        mCenterImg.setImageResource(resId);
    }

    /**
     * @return 标题栏文本
     */
    public String getTopTitleText() {
        return mTitleText.getText().toString();
    }

    /**
     * @return 获取左边标题文本
     */
    public String getLeftText() {
        return mLeftText.getText().toString();
    }

    /**
     * @return 获取右边的标题文本
     */
    public String getRightText() {
        return mRightText.getText().toString();
    }

    public TextView getRightTextView() {
        return mRightText;
    }

    public ImageView getRightImageView() {
        return mRightImg;
    }

    /**
     * 点击中间的title
     */
    public void doClickTitle() {
        // 开放给子类覆盖
        if (Constant.SystemContext.isDebugLog) {
            showDropDownPopupWindow();
        }
    }

    /**
     * 点击地址栏
     */
    public void doClickAddress(String address) {
        // 开放给子类覆盖
        Intent intent = new Intent(this, CityChooseActivity.class);
        intent.putExtra(CityChooseActivity.TAG_ADDRESS, address);
        startActivity(intent);
    }

    /**
     * 点击中间的img
     */
    private void doClickCenterImg() {
        // 开放给子类覆盖
        showDropDownPopupWindow();
    }

    /**
     * 点击右边text
     */
    public void doClickRightText() {
        // 开放给子类覆盖
    }

    /**
     * 点击左边text
     */
    public void doClickLeftText() {
        // 开放给子类覆盖
    }

    /**
     * 点击右边图标
     */
    public void doClickRightImg() {
        // 开放给子类覆盖
    }

    /**
     * 点击左边图标
     */
    public void doClickLeftImg() {
        // 开放给子类覆盖,默认关闭当前页面
        finish();
    }

    /************************************ end GBaseActivity的标题栏设置方式 ************************************************************************/

    /************************************ start GBaseActivity的其他通用设置 ************************************************************************/
    /**
     * 跳转Activity
     *
     * @param activity
     * @param bundle
     */
    protected void gotoActivity(Class<? extends Activity> activity,
                                Bundle bundle) {
        Intent intent = new Intent(this, activity);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 获取当前activity实例
     *
     * @return
     */
    protected Activity getActivity() {
        return this;
    }

    /**
     * 显示popup菜单
     */
    private void showDropDownPopupWindow() {
        if (Constant.SystemContext.isDebugLog) {
            // 部分机型没有菜单键，此处作为查看日志的入口
            if (mPopupWindow == null) {
                initTestPopupWindow();
            }
            mPopupWindow.showAsDropDown(mTopbar, 0, 0);
            Toast.makeText(this, "debug模式开启中，可查看日志和测试ui", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (isUsePx) {
            AbViewUtil.scaleContentView(mMiddleContent);
            MaterialListAdapter.isNeedSacleItem = isUsePx;
        }
    }

}
